import { bulidURL } from "../helpers/url";

export type Method =
    | 'get'
    | 'post'
    | 'put'
    | 'delete'
    | 'patch'
    | 'head'
    | 'options';

export interface AxiosRequestConfig {
    url: string;
    method?: Method;
    data?: any;
    params?: Record<string, unknown>;
}

export interface AxiosResponse<T > {
    data: T;
    status: number;
    statusText: string;
    headers: Record<string, string>;
    config: AxiosRequestConfig;
}

function processConfig (config: AxiosRequestConfig): void {
    config.url = transformUrl(config)
  }
  
  function transformUrl (config: AxiosRequestConfig): string {
    const { url, params } = config
    return bulidURL(url, params)
  }

const request = async <T>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> => {
    const { method = 'get', data} = config;

    
    processConfig(config);

    const fullUrl = config.url;
    console.log(config.url);
    const response = await fetch(fullUrl, {
        method: method.toUpperCase(),
        headers: {
            'Content-Type': 'application/json',
        },
        body: method === 'get' ? undefined : JSON.stringify(data),
    });

    const responseData: T = await response.json();

    return {
        data: responseData,
        status: response.status,
        statusText: response.statusText,
        headers: {},// 可扩展以处理响应头
        config,
    };
};

export default request;
